﻿using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Office.Interop.Word;

namespace WFL.Office.Word
{
    public class WordApplication : IDisposable
    {
        private readonly object _lock = new object();

        private WordDocuments _documents;
        public WordDocuments Documents
        {
            get
            {
                if (_documents == null)
                {
                    lock (_lock) { if (_documents == null) { _documents = new WordDocuments(_application.Documents) { Application = this }; } }
                }
                return _documents;
            }
        }

        private Application _application;

        public WordApplication()
        {
            _application = new ApplicationClass();
            _application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
            _application.Visible = false;
        }

        /// <summary>
        /// 用于将度量单位由磅转换为厘米
        /// </summary>
        /// <param name="point"></param>
        /// <returns></returns>
        public float PointsToCentimeters(float point)
        {
            return _application.PointsToCentimeters(point);
        }

        public float PointsToInches(float point)
        {
            return _application.PointsToInches(point);
        }

        public float PointsToPixels(float point, bool fVertical=false)
        {
            return _application.PointsToPixels(point, fVertical);
        }


        #region IDisposable 成员

        public void Dispose()
        {
            if (_application != null)
            {
                _application.Quit(WdSaveOptions.wdDoNotSaveChanges, Type.Missing, Type.Missing);
                Marshal.ReleaseComObject(_application);
                _application = null;
            }
        }

        #endregion

    }
}
